<?php

/**
 * 图文内容
 */

namespace Manage\Logic;

class UserconfigLogic extends CommonLogic {
    
	protected $_auto = array(
	    array('uid',UID),
	);
	
	public function info($map){
	    return $this->where($map)->find();
	}
	
	/**
	 * (non-PHPdoc)
	 * @see \Member\Logic\BaseLogic::update()
	 */
	public function update($id = 0){
		/* 获取文章数据 */
		$data = $this->create();
		
		if($data === false){
			return false;
		}
		
		$data['uid'] = UID;
		
		$userconfig = $this->where(array('uid'=>UID))->find();
		
		
		/* 添加或更新数据 */
		if(empty($userconfig)){//新增数据
			$id = $this->add($data);
// 			dump($this->getLastSql());EXIT;
			if(!$id){
				$this->error = '新增详细内容失败！';
				return false;
			}
		} else { //更新数据
			$status = $this->where(array('uid'=>UID))->save($data);
			if(false === $status){
				$this->error = '更新详细内容失败！';
				return false;
			}
		}
		
		return true;
	}
	
	/**
	 * 获取某个用户信息
	 */
	public function detail($uid = UID){
	    $map = array(
	        'uid'=>$uid,
	    );
	    return $this->where($map)->find();
	}
	
	/**
	 * (non-PHPdoc)
	 * @see \Member\Logic\BaseLogic::autoSave()
	 */
	public function autoSave($id = 0){
		 
	}
	
	/**
	 * 添加消息
	 */
	public function saveData($text){
		
		$map = array(
				'uid'=>UID,
				'text'=>$text,
		);
		//查找之前是否存在该记录，如果存在，直接返回原来的id
		$textmsg = $this->where($map)->find();
		
		if($textmsg['id'] > 0){
		    return $textmsg['id'];
		}
		
	    $data = array(
	        'uid'=>UID,
	    	'createtime'=>time(),
	    	'text'=>$text,
	    );
	    return $this->add($data);
	}
	
	/**
	 * 获取用户的access_token信息
	 */
	public function access_token($uid = UID){
		
		//从缓存中读取access_token
		$access_token = S('WECHAT_ACCESS_TOKEN_'.$uid);
		
		if(!empty($access_token) && isset($access_token['access_token'])){
		    return $access_token;
		}
		
		//如果缓存不存在，那么就直接重新获取
	    $api = $this->where(array('uid'=>UID))->find();
	    
	    if(empty($api['appid']) || empty($api['appsecret'])){
	        return array('errcode'=>0,'errmsg'=>'未设置appid和appsecret');
	    }
	    
	    $res = \Com\Wechat\ThinkWechat::access_token($api['appid'], $api['appsecret']);
	    
	    if(!empty($res['access_token'])){
	    	S('WECHAT_ACCESS_TOKEN_'.$uid,$res,array('type'=>'file','expire'=>$res['expires_in']));
	    }
	    
	    return $res;
	    
	}
}